package com.xwb.controller;

import com.xwb.dao.UserDao;
import com.xwb.domain.ResponseResult;
import com.xwb.domain.User;
import com.xwb.service.LoginServcie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @Autowired
    private LoginServcie loginServcie;
    //    @Autowired
//    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private UserDao userDao;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user) {
        String userId = user.getUserId();
        String password = user.getPassword();

        if (userId == null || password == null) {
            throw new RuntimeException("userId 和 password 不能为空");
        }

        return loginServcie.login(user);
    }


    @PostMapping("/user/register")
    public Result register(@RequestBody User user) {
        boolean flag = true;
        String password = user.getPassword();
        if (password == null) {
            flag = false;
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        userDao.userRegister(user);
        userDao.updateEncryptedPassword(user.getUserName(), encode);
        //设置默认角色
        userDao.setUserNormalRole(user.getUserId());
        String msg = flag ? "注册成功" : "注册失败";
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, msg);

    }

    @RequestMapping("/user/logout")
    public ResponseResult logout() {
        return loginServcie.logout();
    }
}
